<?php

namespace App\Modules\Index\Services;
use Config;
use  App\Modules\Index\Models\Prescription;
use  App\Modules\Index\Models\Insulin;
use  App\Modules\Index\Models\Medicinal;
use App\Modules\Index\Models\Warning;
use  App\Modules\Index\Models\Defaultmedicinal;
use App\Modules\Index\Models\SetMedicinal;
use App\Modules\User\Models\User;
use GuzzleHttp;
use App\Modules\Index\Models\Glucose;
use Illuminate\Support\Facades\Log;
use App\Modules\System\Services\SetMedicinalService;
use DB;
use Guzzle\Http\Client;

class PrescriptionService
{

    /**
     * 建议报告
     * @param $user_id
     */
    public static function userPrescription($user_id){

        $group_id =  Prescription::where('user_id',$user_id)->where('status',1)->orderBy('audit_at','desc')->value('group_id');
        $res = Prescription::where('group_id',$group_id)->where('status',1)->where('user_id',$user_id)->select('id','group_id','meals','doctor_id','audit_at','is_read')->orderBy('meals','asc')->get()->toArray();
        $data = array();
//        p($res);
        if($res){
            Prescription::where('user_id',$user_id)->where('is_read',0)->update(['is_read'=>1]);
            $start = date('Y-m-d 00:00:00');
            $end = date('Y-m-d 23:59:59');
            foreach($res as $value){
                if($value['meals'] == 1) $meals = 'breakfast';
                if($value['meals'] == 2) $meals = 'lunch';
                if($value['meals'] == 3) $meals = 'dinner';
                if($value['meals'] == 4) $meals = 'bedtime';
                $data[$meals] =  Prescription::where('group_id',$value['group_id'])->where('meals',$value['meals'])->where('status',1)->select('id','meals','insulin_name_en','insulin_name_cn','insulin_type','insulin_preparation','final_units','audit_at')->orderBy('meals','asc')->get()->toArray();
//                p( $data[$value['meals']]);
//                //查询建议报告是否采纳
                foreach( $data[$meals] as $k => $v){
                    $insulin = Insulin::where('user_id',$user_id)->where('prescription_id',$v['id'])->whereBetween('maked_at',[$start,$end])->value('id');
                    if($insulin) $data[$meals][$k]['is_adoption'] = 1; //采纳
                        else $data[$meals][$k]['is_adoption'] = 0; //未采纳
                }
            }
            //医生建议
            $data['doctor_signature'] = DB::table('doctor')->where('id',$res[0]['doctor_id'])->value('signature');
            $data['doctor_signature'] = env('APP_DOMAIN'). $data['doctor_signature'];
            $data['doctor_recommend'] = Warning::where('group_id',$res[0]['group_id'])->where('type','2')->value('content');
            $data['audit_at'] = $res[0]['audit_at'];
            $data['is_update'] = 1;
            if(strtotime($data['audit_at']) < (time()-86400*3)) $data['is_update'] = 0;
        }
        return $data;
    }

    /**
     * @param $user_id
     * @return array
     * 用户用药记录列表
     */
    public static function userMedicinal($user_id){
        $param['user_id'] = $user_id;
        $param['fields'] = 'meals';
        $res = SetMedicinal::from('set_medicinal AS S')->select(['S.id','S.user_id','S.medicinal_id','S.meals','S.insulin_dosage','S.status','M.medicinal_cn','M.medicinal_en','M.insulin_type','M.insulin_preparation'])->leftJoin('medicinal AS M','M.id','=','S.medicinal_id')
            ->where('S.user_id',$param['user_id'])->where('S.status',1)->where('M.status',1)->where('insulin_dosage','>',0)->get()->toArray();
        $data = array();
        if($res){
            $start = date('Y-m-d 00:00:00');
            $end = date('Y-m-d 23:59:59');
            //查询建议报告是否采纳
            foreach( $res as $k => $v){
                $where = [
                    'user_id' => $user_id,
                    'prescription_id'=>0,
                    'type' =>2,
                    'meals' =>$v['meals'],
                    'insulin_name_en' => $v['medicinal_en'],
                    'insulin_type' => $v['insulin_type'],
                    'insulin_preparation' => $v['insulin_preparation']
                ];
                $insulin = Insulin::where($where)->whereBetween('maked_at',[$start,$end])->value('id');
                if($insulin) $res[$k]['is_adoption'] = 1; //采纳
                else $res[$k]['is_adoption'] = 0; //未采纳

                if($v['meals'] == 1){
                    $data['breakfast'][] = $res[$k];
                }else if($v['meals'] == 2){
                    $data['lunch'][] = $res[$k];
                }else if($v['meals'] == 3){
                    $data['dinner'][] = $res[$k];
                }else if($v['meals'] == 4){
                    $data['bedtime'][] = $res[$k];
                }



            }
        }
        return $data;
    }


    /**
     * @param $user_id
     * @return mixed
     * 用户推荐用药
     */
    public static function userDefaultMedicinal($user_id){
        $sara_id = Defaultmedicinal::where('default_type','SARA')->where('status',1)->where('user_id',$user_id)->value('medicinal_id');
        $data = array();
        if($sara_id){
            $data['userSara'] = Medicinal::where('id',$sara_id)->select('medicinal_en as insulinName','insulin_type as insulinType','insulin_preparation as insulinPreparation')->first()->toArray();

        }

        $basal_id = Defaultmedicinal::where('default_type','BASAL')->where('status',1)->where('user_id',$user_id)->value('medicinal_id');
        if($basal_id){
            $data['userBase'] = Medicinal::where('id',$basal_id)->select('medicinal_en as insulinName','insulin_type as insulinType','insulin_preparation as insulinPreparation')->first()->toArray();

        }

        return $data;

    }

    /**
     * @param $user_id
     * 用户手动配置用药情况
     */
    public static function userSetMedicinal($user_id){
        $res = SetMedicinal::leftJoin('medicinal','set_medicinal.medicinal_id','medicinal.id')
            ->where('set_medicinal.user_id',$user_id)
            ->where('set_medicinal.status',1)
            ->where('medicinal.status',1)
            ->select('set_medicinal.id','set_medicinal.meals','set_medicinal.medicinal_id','set_medicinal.insulin_dosage','medicinal.medicinal_en','medicinal.insulin_type','medicinal.insulin_preparation')
            ->groupBy('medicinal_id')
            ->get()->toArray();

        return $res;
    }

    /**
     * 用户的血糖数据
     */

    public static function userGlucose($user_id){
        //用户最新生成报告时间
        $time = Prescription::where('user_id',$user_id)->orderBy('id','desc')->value('created_at');
        if (empty($time)) {
            $res =  Glucose::where('user_id',$user_id)->select('created_at as readingTime','glu as bloodSugarLevel')->get()->toArray();
        }else{
            $res = Glucose::where('user_id',$user_id)->where('created_at','>=',$time)->select('created_at as readingTime','glu as bloodSugarLevel')->get()->toArray();
        }
        return $res;
    }

    /**
     * 定时任务获取VIP用户建议报告
     */

    public static function vipUserRecommend(){

        //查询VIP用户
        $uinfo = User::where('status',1)->where('vip',1)->select('id')->get()->toArray();
//        p($uinfo);
        foreach($uinfo as $value){
            //查询最新建议报告时间
            $userDate = Prescription::where('user_id',$value['id'])->orderBy('id','desc')->value('created_at');
            if(empty($userDate) || (time()-strtotime($userDate))>3*86400 ){
                PrescriptionService::getPrescription($value['id']);
            }
        }
    }

    /**
     * 调用第三方接口获取用户建议报告
     *
     */
    public static function getPrescription($user_id){
        $appid = Config::get('app.appid');
        $appkey = Config::get('app.appkey');
        $nonce = base64_encode(time().'|ysts8888');
        $signature = md5($appkey. '|' .$appid. '|' .$nonce);
        $url = 'https://interopxtserver.chinacloudsites.cn/api/interop/createRecommendation/'.$appid.'/'.$nonce.'/'.$signature;
//echo $appid.'//'.$nonce.'//'.$signature;
        //医生配置用药
        $res = PrescriptionService::userDefaultMedicinal($user_id);

        if($res){

//            echo $user_id;die;

            //用户用药
            $userMedicinal = PrescriptionService::userSetMedicinal($user_id);
            $Insulin1 = [
                "insulinName"=> isset($userMedicinal[0]['medicinal_en'])?$userMedicinal[0]['medicinal_en']:'NONE',
                "insulinType"=> isset($userMedicinal[0]['insulin_type'])?$userMedicinal[0]['insulin_type']:'NONE',
                "insulinPreparation"=> isset($userMedicinal[0]['insulin_preparation'])?$userMedicinal[0]['insulin_preparation']:'UNKNOWN'
            ];


            //胰岛素1的用药时间段
            if(isset($userMedicinal[0])){
                $Insulin1_BeforeBreakfastUnits = SetMedicinal::where('user_id',$user_id)->where('status',1)->where('medicinal_id',$userMedicinal[0]['medicinal_id'])->where('meals',1)->value('insulin_dosage');
                $Insulin1_BeforeLunchUnits = SetMedicinal::where('user_id',$user_id)->where('status',1)->where('medicinal_id',$userMedicinal[0]['medicinal_id'])->where('meals',2)->value('insulin_dosage');
                $Insulin1_BeforeDinnerUnits = SetMedicinal::where('user_id',$user_id)->where('status',1)->where('medicinal_id',$userMedicinal[0]['medicinal_id'])->where('meals',3)->value('insulin_dosage');
                $Insulin1_BeforeBedUnits = SetMedicinal::where('user_id',$user_id)->where('status',1)->where('medicinal_id',$userMedicinal[0]['medicinal_id'])->where('meals',4)->value('insulin_dosage');
            }

            $Insulin2 = [
                "insulinName"=> isset($userMedicinal[1]['medicinal_en'])?$userMedicinal[1]['medicinal_en']:'NONE',
                "insulinType"=> isset($userMedicinal[1]['insulin_type'])?$userMedicinal[1]['insulin_type']:'NONE',
                "insulinPreparation"=> isset($userMedicinal[1]['insulin_preparation'])?$userMedicinal[1]['insulin_preparation']:'UNKNOWN'
            ];

            //胰岛素2的用药时间段
            if(isset($userMedicinal[1])){
                $Insulin2_BeforeBreakfastUnits = SetMedicinal::where('user_id',$user_id)->where('status',1)->where('medicinal_id',$userMedicinal[1]['medicinal_id'])->where('meals',1)->value('insulin_dosage');
                $Insulin2_BeforeLunchUnits = SetMedicinal::where('user_id',$user_id)->where('status',1)->where('medicinal_id',$userMedicinal[1]['medicinal_id'])->where('meals',2)->value('insulin_dosage');
                $Insulin2_BeforeDinnerUnits = SetMedicinal::where('user_id',$user_id)->where('status',1)->where('medicinal_id',$userMedicinal[1]['medicinal_id'])->where('meals',3)->value('insulin_dosage');
                $Insulin2_BeforeBedUnits = SetMedicinal::where('user_id',$user_id)->where('status',1)->where('medicinal_id',$userMedicinal[1]['medicinal_id'])->where('meals',4)->value('insulin_dosage');
            }
            //查询用户基本信息
            $userInfo = User::getUserInfoArr($user_id);
            $HeightMajor =floor($userInfo['height']/100);

            $HeightMinor = $userInfo['height']%100;
            //用户基本配置信息
            $user_meals = diningTimeService::mealsTime($user_id);
    //        p($user_meals);
            if($userInfo['gender'] == 1) $gender = 'MALE';
            else if($userInfo['gender'] == 2) $gender = 'FEMALE';

            //查询用户血糖数据
            $meterReadings = PrescriptionService::userGlucose($user_id);
            if(!empty($meterReadings)){
                $data = [
                    "OrgPatientID"=> $user_id,
                    "MRN"=> "None",
                    "defaultSARAInsulin"=> $res['userSara'],
                    "defaultBasalOrIntermediateInsulin"=>$res['userBase'],
                    "Insulin1"=> $Insulin1,
                    "Insulin2"=> $Insulin2,
                    "DateOfBirth"=> $userInfo['birth_at'],
                    "Gender"=> $gender,
                    "HeightMajor"=> $HeightMajor,
                    "HeightMinor"=> $HeightMinor,
                    "Weight"=> round($userInfo['weight']),

                    "Insulin1_BeforeBreakfastUnits"=> isset($Insulin1_BeforeBreakfastUnits)?$Insulin1_BeforeBreakfastUnits:0,
                    "Insulin1_BeforeLunchUnits"=> isset($Insulin1_BeforeLunchUnits)?$Insulin1_BeforeLunchUnits:0,
                    "Insulin1_BeforeDinnerUnits"=> isset($Insulin1_BeforeDinnerUnits)?$Insulin1_BeforeDinnerUnits:0,
                    "Insulin1_BeforeBedUnits"=> isset($Insulin1_BeforeBedUnits)?$Insulin1_BeforeBedUnits:0,

                    "Insulin2_BeforeBreakfastUnits"=> isset($Insulin2_BeforeBreakfastUnits)?$Insulin2_BeforeBreakfastUnits:0,
                    "Insulin2_BeforeLunchUnits"=> isset($Insulin2_BeforeLunchUnits)?$Insulin2_BeforeLunchUnits:0,
                    "Insulin2_BeforeDinnerUnits"=> isset($Insulin2_BeforeDinnerUnits)?$Insulin2_BeforeDinnerUnits:0,
                    "Insulin2_BeforeBedUnits"=> isset($Insulin2_BeforeBedUnits)?$Insulin2_BeforeBedUnits:0,

                    "MealTimeBreakfastStart"=> date('Y-m-d').' '.$user_meals['mealsconf'][0]['start_time'].':00',
                    "MealTimeBreakfastEnd"=> date('Y-m-d').' '.$user_meals['mealsconf'][0]['end_time'].':00',
                    "BreakfastPrePrandLow"=> $user_meals['mealsconf'][0]['before_low'],
                    "BreakfastPrePrandHigh"=> $user_meals['mealsconf'][0]['before_high'],
                    "BreakfastPostPrandLow"=> $user_meals['mealsconf'][0]['after_low'],
                    "BreakfastPostPrandHigh"=> $user_meals['mealsconf'][0]['after_high'],

                    "MealTimeLunchStart"=> date('Y-m-d').' '.$user_meals['mealsconf'][1]['start_time'].':00',
                    "MealTimeLunchEnd"=> date('Y-m-d').' '.$user_meals['mealsconf'][1]['end_time'].':00',
                    "LunchPrePrandLow"=> $user_meals['mealsconf'][1]['before_low'],
                    "LunchPrePrandHigh"=> $user_meals['mealsconf'][1]['before_high'],
                    "LunchPostPrandLow"=> $user_meals['mealsconf'][1]['after_low'],
                    "LunchPostPrandHigh"=> $user_meals['mealsconf'][1]['after_high'],

                    "MealTimeDinnerStart"=> date('Y-m-d').' '.$user_meals['mealsconf'][2]['start_time'].':00',
                    "MealTimeDinnerEnd"=> date('Y-m-d').' '.$user_meals['mealsconf'][2]['end_time'].':00',
                    "DinnerPrePrandLow"=> $user_meals['mealsconf'][2]['before_low'],
                    "DinnerPrePrandHigh"=> $user_meals['mealsconf'][2]['before_high'],
                    "DinnerPostPrandLow"=> $user_meals['mealsconf'][2]['after_low'],
                    "DinnerPostPrandHigh"=> $user_meals['mealsconf'][2]['after_high'],

                    "MealTimeBedtimeStart"=> date('Y-m-d').' '.$user_meals['mealsconf'][3]['start_time'].':00',
                    "MealTimeBedtimeEnd"=> date('Y-m-d').' '.$user_meals['mealsconf'][3]['end_time'].':00',
                    "BedTimePrePrandLow"=> $user_meals['mealsconf'][3]['before_low'],
                    "BedTimePrePrandHigh"=> $user_meals['mealsconf'][3]['before_high'],
                    "BedTimePostPrandLow"=> $user_meals['mealsconf'][3]['before_low'],
                    "BedTimePostPrandHigh"=>$user_meals['mealsconf'][3]['before_high'],
                    "HbA1cLevel"=> 0,
                    "MeterReadings"=> [
                        "bloodSugarUnits"=> "MMOLL",
                        "MeterReadings"=> $meterReadings

                    ],
                    "glucoseUnits"=> "MMOLL",
                    "measurementSystem"=> "METRIC",
                    "CalculationMode"=> "CONSERVATIVE",
                    "RecencyDays"=> 4
                ];
                Log::useDailyFiles(storage_path('logs/recommedation/recommedation.log'));
                $data_log = json_encode($data);
                Log::info($data_log);
                $client = new GuzzleHttp\Client();
                $response =  $client->request('POST',$url,['json'=>$data,'http_errors' => false]);
                $code = $response->getStatusCode();
                Log::info('用户ID：'.$user_id.'请求返回code:'.$code);
                if($code == 200){
                    $result = json_decode($response->getBody()->getContents(),true);
                    Log::info($result);

                    if(isset($result['iaMessage']) && isset($result['algoVersion'])){
                        if($result['iaMessage']['errorCode'] == 0 && $result['algoVersion']['iaMessage']['errorCode'] == 0){
                            $rst = PrescriptionService::inputRecommendation($result,$user_id);

                        }else{
                            $err['user_id'] = $user_id;
                            $err['error_code'] = $result['iaMessage']['errorCode'];
                            $err['error_message'] = $result['iaMessage']['errorMessage'];;
                            $err['create_at'] = date('Y-m-d H:i:s');
                            $err['update_at'] = date('Y-m-d H:i:s');
                            DB::table('error_table')->insert($err);

                            //查询警告
                            $warning_message = DB::table('warning_tab')->where('warning_name',$result['iaMessage']['errorCode'])->value('warning_message');
                            if(!empty($warning_message)){
                                $insert['user_id'] = $user_id;
                                $insert['content'] = $warning_message;
                                $insert['type'] = 1;
                                Warning::create($insert);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @param $data
     * 录入建议报告
     */
    public static function inputRecommendation($data,$user_id){
        if(isset($data['recommendationList'])){
            $recommendation = $data['recommendationList'];
            $group_id = time().rand(10000,99999);
            DB::beginTransaction();
            try{

                foreach($recommendation as $value){
                    if($value['recommendationType'] != 'NONE' && $value['recommendationType'] != 'INVALID_REGIME'){
                        switch($value['dosageTime']){
                            case 'BEFORE_BREAKFAST';
                                $insert['meals'] = 1;
                                break;
                            case 'BEFORE_LUNCH';
                                $insert['meals'] = 2;
                                break;
                            case 'BEFORE_DINNER';
                                $insert['meals'] = 3;
                                break;
                            case 'BEFORE_BEDTIME';
                                $insert['meals'] = 4;
                                break;
                        }

                        $insert['user_id'] = $user_id;
                        $insert['type'] = 1;
                        $insert['group_id'] = $group_id;
                        $insert['insulin_name_en'] = $value['insulinName'];
                        $insert['insulin_name_cn'] = PrescriptionService::medicinalCn($value['insulinName'],$value['insulinType'],$value['insulinPreparation']);
                        $insert['recommendation_type'] = $value['recommendationType'];
                        $insert['insulin_type'] = $value['insulinType'];
                        $insert['adjustment_units'] = $value['adjustmentUnits'];
                        $insert['initial_units'] = $value['initialUnits'];
                        $insert['final_units'] = $value['finalUnits'];
                        $insert['insulin_preparation'] = $value['insulinPreparation'];
                        Prescription::create($insert);
                    }
                }

                if(count($data['warningsList'])>0){
                    PrescriptionService::inputWarning($data['warningsList'],$user_id,$group_id);

                }

                DB::commit();
                return 'success';
            }catch (\Exception $exception) {
                DB::rollBack();
                return $exception->getMessage();
            }
        }





    }

    /**
     * @param $data
     * 用户警告
     */
    public static function inputWarning($data,$user_id,$group_id){
        foreach($data as $value){
            $content = DB::table('warning_tab')->where('warning_name',$value['warningID'])->value('warning_message');
            $insert['user_id'] = $user_id;
            $insert['group_id'] = $group_id;
            $insert['content'] = $content;
            $insert['content_en'] = $value['warningText'];
            $insert['type'] = 1;
            Warning::create($insert);
        }
    }

    public static function medicinalCn($medicinal_en,$insulin_type,$insulin_preparation){
        return Medicinal::where('medicinal_en',$medicinal_en)->where('insulin_type',$insulin_type)->where('insulin_preparation',$insulin_preparation)->value('medicinal_cn');
    }

}